#!/usr/bin/env python3

from flask import Flask, request
import threading
import base64
import os

from dotenv import load_dotenv

from espeak import execute_espeak, repeatPlayEspeak
from play import playMp3, repeatPlayMp3, playAlert, playAccept, playDeny, playWarning, playError
from button_handle import setBtnHandler
from warning import sendSupportAccept, sendSupportDeny, sendWarning
from socket_client import startWebSocket

app = Flask(__name__)
load_dotenv()

workOrderId = None
stopPlay = None

devCode = os.getenv('id')

@app.route('/', methods=['post', 'get'])
def doSpeak():
  text = request.get_data(as_text=True)
  text = text.replace(' ', '_')
  print(text)
  threading._start_new_thread(execute_espeak, (text, ))
  return 'ok'

@app.route('/mp3', methods=['post'])
def play():
  b64Mp3 = request.get_data(as_text=True)
  # mp3 = base64.b64decode(b64Mp3)
  threading._start_new_thread(playMp3, (b64Mp3, ))
  return 'ok'

def stop():
  global stopPlay
  if stopPlay is not None:
    stopPlay.set()
    stopPlay = None

def socketCB(msg):
  global workOrderId
  global stopPlay
  stop()
  workOrderId = msg['workOrderId']
  msgType = msg['type']
  print(msg)
  playAlert()
  if msgType == 'mp3':
    stopPlay = repeatPlayMp3(msg['voice'])
  else:
    stopPlay = repeatPlayEspeak(msg['voice'])

def acceptHandler():
  global workOrderId
  global stopPlay
  stop()
  ret = sendSupportAccept(devCode, 1, workOrderId)
  if 'ret' in ret and ret['ret'] < 0:
    playError()
  else:
    playAccept()

def denyHandler():
  global workOrderId
  global stopPlay
  stop()
  ret = sendSupportDeny(devCode, 0, workOrderId)
  if 'ret' in ret and ret['ret'] < 0:
    playError()
  else:
    playDeny()

def warningHandler():
  ret = sendWarning(devCode)
  if 'ret' in ret and ret['ret'] < 0:
    playError()
  else:
    playWarning()

if __name__ == '__main__':
  setBtnHandler(acceptHandler, denyHandler, warningHandler)
  url = os.getenv('wsUrl') + '/' + os.getenv('id')
  stopSocket = startWebSocket(url, socketCB)
  app.run(host='0.0.0.0')
  stopSocket()
  if stopPlay is not None:
    stopPlay.set()
